package com.reggie.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.backend.DishEnum;
import com.reggie.common.enums.backend.SetmealEnum;
import com.reggie.module.entity.dto.setmealDto.SetmealDto;
import com.reggie.module.entity.po.Dish;
import com.reggie.module.entity.po.Setmeal;
import com.reggie.module.entity.po.SetmealDish;
import com.reggie.module.entity.vo.setmealVo.SetmealVo;
import com.reggie.module.mapper.CategoryMapper;
import com.reggie.module.mapper.DishMapper;
import com.reggie.module.mapper.SetmealDishMapper;
import com.reggie.module.mapper.SetmealMapper;
import com.reggie.module.service.DishService;
import com.reggie.module.service.SetmealDishService;
import com.reggie.module.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.reggie.common.Constant.LOGIN_SESSION;

/**
 * @Author 早睡蛋
 * @Date 2022/9/17 14:29:22
 * @Desc:
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishMapper dishMapper;

    @Override
    @Transactional
    public ResultResponseVo saveSetmeal(SetmealDto setmealDto, HttpServletRequest request) {
        Setmeal setmeal = setmealDto.addSetmeal(setmealDto, request);
        int insertSetmeal = setmealMapper.insert(setmeal);
        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        addSetmealDishes(setmealDishes, setmealId, request);
        boolean saveBatch = setmealDishService.saveBatch(setmealDishes);
        if (insertSetmeal > 0 && saveBatch) {
            return SetmealEnum.ADD_OK.getResultResponseVo();
        }
        return SetmealEnum.ADD_FAIL.getResultResponseVo();
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public ResultResponseVo selectByPage(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize, true);
        QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
        setmealQueryWrapper.select("id", "name", "category_id", "image", "status", "price", "update_time")
                .last("order by update_time desc");
        if (StringUtils.isNotEmpty(name)) {
            setmealQueryWrapper.like("name", name);
        }
        IPage<Setmeal> setmealIPage = setmealMapper.selectPage(setmealPage, setmealQueryWrapper);
        List<Setmeal> setmealList = changeToSetmealListVo(setmealIPage.getRecords());
        setmealIPage.setRecords(setmealList);
        return SetmealEnum.SUCCESS.getResult().setData(setmealIPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public ResultResponseVo deleteSetmeal(List<Long> ids) {
        int flag = countStatusBeforeSetmealDelete(ids);
        if (flag == 1) {
            return SetmealEnum.STATUS_ON.getResultResponseVo();
        }
        int deleteBatchIds = setmealMapper.deleteBatchIds(ids);

        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.in(SetmealDish::getSetmealId, ids);
        boolean remove = setmealDishService.remove(setmealDishQueryWrapper);

        if (deleteBatchIds > 0 && remove) {
            return SetmealEnum.DEL_OK.getResultResponseVo();
        }
        return SetmealEnum.DEL_FAIL.getResultResponseVo();
    }

    @Override
    public ResultResponseVo getListById(Long categoryId, Integer status) {
        QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
        setmealQueryWrapper.select("id", "name", "image", "price")
                .eq("category_id", categoryId);
        if (status==null){
            setmealQueryWrapper.eq("status", 1);
        }else {
            setmealQueryWrapper.eq("status", status);
        }
        List<Setmeal> setmealList = setmealMapper.selectList(setmealQueryWrapper);
        return SetmealEnum.SUCCESS.getResultResponseVo().setData(setmealList);

    }

    /**
     * 获取套餐中的菜品信息（前台）
     * @param id
     * @return
     */
    @Override
    public ResultResponseVo getMealDishDetails(Long id) {
        QueryWrapper<SetmealDish> setmealDishQueryWrapper = new QueryWrapper<>();
        setmealDishQueryWrapper.eq("setmeal_id",id);
        List<SetmealDish> setmealDishList = setmealDishMapper.selectList(setmealDishQueryWrapper);
        findImage(setmealDishList);
        return SetmealEnum.SUCCESS.getResultResponseVo().setData(setmealDishList);
    }

    /**
     * 修改套餐前获取套餐信息
     * @param id
     * @return
     */
    @Override
    public ResultResponseVo getSetmealById(Long id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        SetmealVo setmealVo = setSetmealVo(setmeal);
        return SetmealEnum.SUCCESS.getResultResponseVo().setData(setmealVo);

    }

    public void addSetmealDishes(List<SetmealDish> setmealDishes, Long setmealId, HttpServletRequest request) {
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealId);
            setmealDish.setCreateTime(LocalDateTime.now());
            setmealDish.setUpdateTime(LocalDateTime.now());
            Long empId = (Long) request.getSession().getAttribute(LOGIN_SESSION);
            setmealDish.setCreateUser(empId);
            setmealDish.setUpdateUser(empId);
        }
    }

    /**
     * 通过category_id查询对应的分类名称
     *
     * @param setmeals
     * @return
     */
    public List<Setmeal> changeToSetmealListVo(List<Setmeal> setmeals) {
        List<Setmeal> setmealList = new ArrayList<>();
        for (Setmeal setmeal : setmeals) {
            String categoryName = categoryMapper.selectNameById(setmeal.getCategoryId());
            setmeal.setCategoryName(categoryName);
            setmealList.add(setmeal);
        }
        return setmealList;
    }

    public int countStatusBeforeSetmealDelete(List<Long> ids) {
        List<Setmeal> setmealList = new ArrayList<>();
        for (Long id : ids) {
            QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
            setmealQueryWrapper.select("status")
                    .eq("status", 1)
                    .eq("id", id);
            Setmeal setmeal = setmealMapper.selectOne(setmealQueryWrapper);
            if (setmeal != null) {
                setmealList.add(setmeal);
            }
        }
        if (setmealList.size() > 0) {
            return 1;
        }
        return 0;
    }

    public void findImage(List<SetmealDish> setmealDishList){
        for (SetmealDish setmealDish : setmealDishList) {
            QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
            dishQueryWrapper.select("image").eq("id",setmealDish.getDishId());
            Dish dish = dishMapper.selectOne(dishQueryWrapper);
            setmealDish.setImage(dish.getImage());
        }
    }


    public SetmealVo setSetmealVo(Setmeal setmeal){
        SetmealVo setmealVo = new SetmealVo();
        QueryWrapper<SetmealDish> setmealDishQueryWrapper = new QueryWrapper<>();
        setmealDishQueryWrapper.select("id","setmeal_id","dish_id","name","price","copies")
                .eq("setmeal_id",setmeal.getId());
        List<SetmealDish> setmealDishList = setmealDishMapper.selectList(setmealDishQueryWrapper);
        setmealVo.setId(setmeal.getId());
        setmealVo.setCategoryId(setmeal.getCategoryId());
        setmealVo.setName(setmeal.getName());
        setmealVo.setPrice(setmeal.getPrice());
        setmealVo.setImage(setmeal.getImage());
        setmealVo.setDescription(setmeal.getDescription());
        setmealVo.setSetmealDishes(setmealDishList);
        return setmealVo;
    }

}
